import React from 'react';
import { Block } from 'fs-flex/lib';
import {InputItem,Button,Toast} from 'antd-mobile';
import { createForm } from 'rc-form';
import SmsService from '../../services/smsService' ;
import Canstant from '../../utils/constant'
import styles from './index.less'
class VerificationCode extends React.Component{
    state={
        timer:null,//定时器ID
        phone:null,// 电话号码
        verificationCodeValue:null,// 验证码
        verificationCode:{
            disabled:false,
            surplusTime:this.props.timeout?this.props.timeout:300,
            message:this.props.btnText?this.props.btnText:'获取验证码'
        },
    }
        // 点击获取验证码按钮
    async getVerificationCode(){
        // TODO 从后台获取短信验证码
        const {phone} = this.state
        const phoneNo = phone.replace(/\s/g, "")
        const isNullPhone=this.phonevalidate(phoneNo)
        if(!isNullPhone){
            return
        }
        const {code ,data,msg}=await SmsService.sendIdentify(phoneNo)
        if(code!==Canstant.responseOK){
            Toast.fail(msg?msg:'获取短信验证码异常！',3)
            return
        }else{
            this.setState({
                verificationCode:{
                    disabled:true,
                    surplusTime:60,
                    message:`获取验证码`,
                }
                })
                this.aTimer()
        }
    
    }
    aTimer() {
        let {verificationCode:{surplusTime}}=this.state
        let aTimer=setInterval(()=>{
        if(surplusTime===1){
            this.setState({
            timer:null,
            verificationCode:{
                disabled:false,
                surplusTime:60,
                message:'获取验证码',
            },
            })
            clearInterval(aTimer)
            console.log('clear timer run....')
        }else{
            this.setState({
            verificationCode:{
                disabled:true,
                surplusTime:surplusTime--,
                message:this.transformationMsg(surplusTime),
            },
            })
        }
        },1000)
        this.setState({timer:aTimer})
    }

    // 秒转化为：xx分xx秒后可重新发送
    transformationMsg(timeSecond){
        if(timeSecond===null || timeSecond===0){
            return '获取验证码'
        }
        if(timeSecond<=60){
            return `${timeSecond}秒后可重新发送`
        }
        const minute = parseInt(timeSecond/60)
        const second=timeSecond%60
        if(second===0){
            return `${minute}分钟后可重新发送`
        }
        return `${minute}分${second}秒后可重新发送`
    }

    // 电话号码输入监听
    phonevalidate=(val)=>{
        if(!val){
            Toast.fail('请填写手机号码！')
            return false
        }
        var isPhone = /^1\d{10}$/;//手机号码
        if(isPhone.test(val.replace(/\s+/g, ""))){
            return true
        }else{
            Toast.fail('输入手机号码格式错误!')
            return false
        }
    }

    // 验证码输入监听
    codeChange(value){
        const phone=this.state.phone
        this.setState({verificationCodeValue:value})
        this.props.verificationCodeChange(value,phone)
    }

    phoneOnchange(v){
        const verificationCodeValue=this.state.verificationCodeValue
        this.setState({phone:v})
        this.props.verificationCodeChange(verificationCodeValue,v)
    }
    // 组件销毁时清除掉timer
    componentWillUnmount(){
        if(this.state.timer!=null){
        clearInterval(this.state.timer)
        }
    }
    render(){
        let {phoneLabel,codeLabel,lableInline } = this.props;
        const {verificationCode,verificationCodeValue,phone} =this.state
        phoneLabel=phoneLabel?phoneLabel:'手机号（必填）'
        codeLabel=codeLabel?codeLabel:'验证码（必填）'
        return(
            <Block vf>
                <Block vf>
                    {
                        lableInline?null:<Block fs={14}>{phoneLabel}</Block>
                    }
                    <Block mt={5}>
                        <InputItem
                            type="phone"
                            placeholder={phoneLabel}
                            value={phone}
                            onChange={v=>this.phoneOnchange(v)}
                            >{lableInline?phoneLabel:null}</InputItem>
                    </Block>
                </Block>
                <Block mt={10}>
                    {
                        lableInline?null:<Block fs={14}>{codeLabel}</Block>
                    }
                    <Block mt={5} className={styles.codeStyle}>
                        <InputItem
                            onChange={v=>this.codeChange(v)}
                            type="number"
                            value={verificationCodeValue}
                            placeholder={codeLabel}
                            extra={<Button size='small' disabled={verificationCode.disabled} onClick={this.getVerificationCode.bind(this)}>{verificationCode.message}</Button>}
                            >{lableInline?codeLabel:null}</InputItem>
                    </Block>
                </Block>
            </Block>
        )
    }
}

export default createForm()(VerificationCode);
